/*******************************************************************************
 * Copyright 2020 huanggefan.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

package action

import (
	"gitee.com/WisdomClassroom/bank/global"
	"gitee.com/WisdomClassroom/core"
	"gitee.com/WisdomClassroom/core/models"
	"gitee.com/WisdomClassroom/core/protobufs/v1/pb"
	"github.com/jinzhu/gorm"
)

func CreateQuestionBank(req *pb.CreateQuestionBankRequest) *pb.CreateQuestionBankResponse {
	resp := new(pb.CreateQuestionBankResponse)
	var err error

	token := core.NewToken()
	err = token.UnpackToken(req.AuthToken, global.TokenCert)
	if err != nil {
		resp.Status = &pb.ResponseStatus{
			Code:    pb.ResponseStatusCode_OtherError,
			Message: "认证失败： " + err.Error(),
		}
		return resp
	}

	if token.Type != core.UserRoleTypeCodeRoot {
		resp.Status = &pb.ResponseStatus{
			Code:    pb.ResponseStatusCode_OtherError,
			Message: "没有权限",
		}
		return resp
	}

	err = global.DB.Where("course_uuid = ?", req.CourseUUID).
		Not("deleted", true).First(&models.BankCourseBindModel{}).Error
	if err != gorm.ErrRecordNotFound {
		resp.Status = &pb.ResponseStatus{
			Code:    pb.ResponseStatusCode_OtherError,
			Message: "该课程已经存在题库：" + req.CourseUUID,}
		return resp
	}

	manager := &models.UserModel{}
	err = global.DB.Where("uuid = ?", req.ManagerUUID).Not("deleted", true).First(manager).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			global.Logger.Debug("Find UserModel: record not found")
			resp.Status = &pb.ResponseStatus{
				Code:    pb.ResponseStatusCode_OtherError,
				Message: "管理员不存在：" + req.ManagerUUID,
			}
		} else {
			global.Logger.Warning("Find UserModel error: " + err.Error())
			resp.Status = &pb.ResponseStatus{
				Code:    pb.ResponseStatusCode_OtherError,
				Message: "查找管理员错误：" + err.Error(),
			}
		}
		return resp
	}

	course := &models.CourseModel{}
	err = global.DB.Where("uuid = ?", req.CourseUUID).Not("deleted", true).First(course).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			global.Logger.Debug("Find CourseModel: record not found")
			resp.Status = &pb.ResponseStatus{
				Code:    pb.ResponseStatusCode_OtherError,
				Message: "课程不存在：" + req.CourseUUID,
			}
		} else {
			global.Logger.Warning("Find CourseModel error: " + err.Error())
			resp.Status = &pb.ResponseStatus{
				Code:    pb.ResponseStatusCode_OtherError,
				Message: "查找课程错误：" + err.Error(),
			}
		}
		return resp
	}

	bank := &models.BankModel{
		Model:       models.NewModel(),
		Name:        req.Name,
		Description: req.Description,
	}
	bankManager := &models.BankManagerBindModel{
		Model:       models.NewModel(),
		BankUUID:    bank.UUID,
		ManagerUUID: manager.UUID,
	}
	bankCourse := &models.BankCourseBindModel{
		Model:      models.NewModel(),
		BankUUID:   bank.UUID,
		CourseUUID: course.UUID,
	}

	tx := global.DB.Begin()
	err = func() error {
		err = tx.Create(bank).Error
		if err != nil {
			global.Logger.Warning("Create BankModel error: " + err.Error())
			tx.Rollback()
			return err
		}
		err = tx.Create(bankManager).Error
		if err != nil {
			global.Logger.Warning("Create BankManagerBindModel error: " + err.Error())
			tx.Rollback()
			return err
		}
		err = tx.Create(bankCourse).Error
		if err != nil {
			global.Logger.Warning("Create BankCourseBindModel error: " + err.Error())
			tx.Rollback()
			return err
		}
		tx.Commit()
		return nil
	}()
	if err != nil {
		resp.Status = &pb.ResponseStatus{
			Code:    pb.ResponseStatusCode_OtherError,
			Message: "创建题库失败：" + err.Error(),
		}
		return resp
	}

	resp.Status = &pb.ResponseStatus{
		Code:    pb.ResponseStatusCode_Suc,
		Message: "创建题库成功：" + bank.UUID,
	}
	resp.UUID = bank.UUID

	return resp
}
